package com.java.shop.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.common.exception.MyException;
import com.java.common.utils.PageUtils;
import com.java.common.utils.Query;
import com.java.shop.product.dao.CategoryBrandRelationDao;
import com.java.shop.product.entity.BrandEntity;
import com.java.shop.product.entity.CategoryBrandRelationEntity;
import com.java.shop.product.entity.CategoryEntity;
import com.java.shop.product.exception.ProductExceptionEnum;
import com.java.shop.product.service.BrandService;
import com.java.shop.product.service.CategoryBrandRelationService;
import com.java.shop.product.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j
@Service("categoryBrandRelationService")
public class CategoryBrandRelationServiceImpl extends ServiceImpl<CategoryBrandRelationDao, CategoryBrandRelationEntity> implements CategoryBrandRelationService {

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryBrandRelationEntity> page = this.page(
                new Query<CategoryBrandRelationEntity>().getPage(params),
                new QueryWrapper<CategoryBrandRelationEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public void saveDetail(Long categoryId,Long brandId) {
        QueryWrapper<CategoryBrandRelationEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("brand_id",brandId);
        wrapper.eq("catelog_id",categoryId);
        CategoryBrandRelationEntity one = this.getOne(wrapper);
        if(one != null) throw new MyException(ProductExceptionEnum.REPEAT_EXCEPTION.getCode(),ProductExceptionEnum.REPEAT_EXCEPTION.getMsg());
        CategoryEntity categoryEntity = categoryService.getById(categoryId);
        BrandEntity brandEntity = brandService.getById(brandId);
        if(categoryEntity != null && brandEntity != null){
            CategoryBrandRelationEntity cbr = new CategoryBrandRelationEntity();
            cbr.setCatelogId(categoryEntity.getCatId());
            cbr.setCatelogName(categoryEntity.getName());
            cbr.setBrandId(brandEntity.getBrandId());
            cbr.setBrandName(brandEntity.getName());
            this.save(cbr);
        }else{
            log.error("CategoryBrandRelationServiceImpl：mySave关联保存失败");
            throw new MyException(ProductExceptionEnum.BRANDORCATEGORY_NOTFOUND_EXCEPTION.getCode(),ProductExceptionEnum.BRANDORCATEGORY_NOTFOUND_EXCEPTION.getMsg());
        }
    }
}